﻿namespace LocationByAddress
{
    using System;
    using System.Collections.Generic;
    using System.Reactive.Linq;
    using System.Windows;
    using Microsoft.Phone.Controls;
    using WP7Contrib.Services.BingMaps;
    using WP7Contrib.Services.BingMaps.Model;

    public partial class MainPage : PhoneApplicationPage
    {
        private readonly IBingMapsService bingMapsService;

        public MainPage()
        {
            InitializeComponent();

            bingMapsService = new BingMapsService("Your credentials id", "Your app id");

            this.startText.Text = "New York";
            this.finishText.Text = "Seattle";
        }

    private void HandleCalculateRouteClick(object sender, RoutedEventArgs e)
    {
        var waypoints = new List<WayPoint>
                            {
                                new WayPoint {Landmark = new Landmark {AreaName = this.startText.Text}},
                                new WayPoint {Landmark = new Landmark {AreaName = this.finishText.Text}}
                            };

        var criterion = CriterionFactory.CreateRouteSearch(waypoints);
        bingMapsService.CalculateARoute(criterion)
            .ObserveOnDispatcher()
            .Subscribe(this.DisplayRoute, this.FailedRoute);
    }

        private void FailedRoute(Exception exception)
        {
            this.resultStatus.Text = "Failed to calculate a route!";
            this.resultStatus.Text = string.Format("Exception - '{0}'", exception.Message);

            this.resultDistance.Text = string.Empty;
            this.resultDuration.Text = string.Empty;
            this.resultRouteLegs.Text = string.Empty;
            this.routeLegs.ItemsSource = null;
        }

        private void DisplayRoute(RouteSearchResult result)
        {
            this.resultStatus.Text = string.Format("Response: {0} - {1}", result.StatusCode, result.StatusDescription);

            if (result.HasSucceeded)
            {
                this.resultDistance.Text = string.Format("Distance: {0} {1}", result.TravelDistance, result.DistanceUnit);
                this.resultDuration.Text = string.Format("Duration: {0} {1}", result.TravelDuration, result.DurationUnit);

                this.resultRouteLegs.Text = string.Format("Iternary Count: {0}", result.RouteLegs[0].ItineraryItems.Count);

                this.routeLegs.ItemsSource = result.RouteLegs;
            }
        }
    }
}